import logging
from django.dispatch import receiver
from django.db.models.signals import post_save
from .models import MenuModel, PermissionsModel

logger = logging.getLogger("erp")

methods = {
    'GET': '查询',
    'POST': '新增',
    'PUT': '修改',
    'DELETE': '删除',
    'PATCH': '改局部',
}


@receiver(post_save, sender=MenuModel)
def create_menus_permissions(sender, instance, created, **kwargs):
    """
    创建信号监控函数， 信号接收者收到之后自动触发， 创建菜单资源对应的权限
    :param sender:
    :param instance:
    :param created:
    :param kwargs:
    :return:
    """
    if created:
        permission = PermissionsModel()
        logger.info("创建菜单资源对于的权限")
        if isinstance(instance, MenuModel):
            if not instance.parent:  # 因为没有父菜单， 那么menu就是功能模块菜单对象
                permission = PermissionsModel.objects.create(name=instance.name + "的权限", is_menu=True)
                permission.menu = instance
                permission.save()
            else:  # 当前菜单是接口
                for method in methods:
                    # permission = PermissionsModel.objects.create(name=f"{instance.name}的{methods.get('method')}的权限",
                    permission = PermissionsModel.objects.create(name=f"{methods.get('method')}",
                                                                 is_menu=False, method=method, path=instance.url,
                                                                 desc=f"{instance.name}的{methods.get('method')}的权限")
                    permission.menu = instance
                    permission.save()
        else:
            logger.error("当前对象不是MenuModel类型， 所以不需要创建对于的权限数据")
